package com.wuda.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

	/**
	 * 将字符串转换成MD5
	 * @param plainText 待转换字符串
	 * @return MD5字符串
	 */
	public static String stringToMD5(String plainText) {
		byte[] secretBytes = null;
		try {
			secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("没有这个md5算法！");
		}
		String md5code = new BigInteger(1, secretBytes).toString(16);
		for (int i = 0; i < 32 - md5code.length(); i++) {
			md5code = "0" + md5code;
		}
		return md5code;
	}

	/**
	 * 将密码进行MD5加密
	 * @param password 待加密密码
	 * @return MD5加密后的密码
	 */
	public static String passMd5(String password) {
		String salt = "W!.L";
		return Util.stringToMD5(password + salt);
	}

	/**
	 * 判断邮箱是否合法
	 * @param email 待判断的邮箱
	 * @return true合法，false不合法
	 */
	public static boolean isValidEmail(String email) {
		String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
		Pattern pattern = Pattern.compile(emailRegex);
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();
	}
}
